package com.easyoffer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyoffer.common.BaseResponse;
import com.easyoffer.common.DeleteRequest;
import com.easyoffer.common.ErrorCode;
import com.easyoffer.common.util.BlackIpUtil;
import com.easyoffer.common.util.NetUtils;
import com.easyoffer.common.util.ResultUtils;
import com.easyoffer.constant.CommonConstant;
import com.easyoffer.constant.UserConstant;
import com.easyoffer.exception.BusinessException;
import com.easyoffer.model.dto.question.QuestionEsDTO;
import com.easyoffer.model.entity.User;
import com.easyoffer.service.QuestionBankQuestionService;
import com.easyoffer.service.QuestionBankService;
import com.easyoffer.service.QuestionService;
import com.easyoffer.service.UserService;
import com.easyoffer.annotation.RoleCheck;
import com.easyoffer.model.dto.question.QuestionAddRequst;
import com.easyoffer.model.dto.question.QuestionQueryRequest;
import com.easyoffer.model.dto.question.QuestionUpdateRequest;
import com.easyoffer.model.entity.Question;
import com.easyoffer.model.entity.QuestionBankQuestion;
import com.easyoffer.model.vo.QuestionVO;
import com.easyoffer.model.vo.UserVO;
import com.easyoffer.mapper.QuestionMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 何文斌
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2025-03-15 21:09:28
*/
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService {

    @Autowired
    private UserService userService;
    @Autowired
    @Lazy
    private QuestionBankQuestionService questionBankQuestionService;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private QuestionBankService questionBankService;

    @Autowired
    NetUtils netUtils;

    @RoleCheck(mustRole = "admin")
    @Override
    public BaseResponse<Long> addQuestion(QuestionAddRequst questionAddRequst, HttpServletRequest request) {
        if (questionAddRequst == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);

        String title = questionAddRequst.getTitle();
        String content = questionAddRequst.getContent();
        if(StringUtils.isAllBlank(title,content)){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR,"题目和题目内容必填");
        }
        Question question = new Question();
        UserVO loginUser = (UserVO) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        BeanUtil.copyProperties(questionAddRequst,question);
        question.setUserId(loginUser.getId());
        if (this.save(question)){
            return ResultUtils.success(question.getId());
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }

    @RoleCheck(mustRole = "admin")
    @Override
    public BaseResponse<Integer> updateQuestion(QuestionUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        Question question = new Question();
        Long id = updateRequest.getId();
        String title = updateRequest.getTitle();
        String content = updateRequest.getContent();
        String tags = updateRequest.getTags();
        String answer = updateRequest.getAnswer();
        Integer priority = updateRequest.getPriority();
        Integer viewNum = updateRequest.getViewNum();
        Integer thumbNum = updateRequest.getThumbNum();
        Integer favoriteNum = updateRequest.getFavoriteNum();
        Integer needVip = updateRequest.getNeedVip();
        question.setId(id);
        if (StringUtils.isNotBlank(title))
            question.setTitle(title);
        if (StringUtils.isNotBlank(content))
            question.setContent(content);
        if (StringUtils.isNotBlank(tags))
            question.setTags(tags);
        if (StringUtils.isNotBlank(answer))
            question.setAnswer(answer);
        if (priority != null)
            question.setPriority(priority);
        if (viewNum != null)
            question.setViewNum(viewNum);
        if (thumbNum != null)
            question.setThumbNum(thumbNum);
        if (favoriteNum != null)
            question.setFavoriteNum(favoriteNum);
        if (needVip != null)
            question.setNeedVip(needVip);
        if (this.updateById(question)){
            return ResultUtils.success(1);
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }

    @RoleCheck(mustRole = "admin")
    @Override
    public BaseResponse<Boolean> deleteQuestion(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() == null)
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        if (this.removeById(deleteRequest.getId())){
            return ResultUtils.success(true);
        }
        return ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }
    @Override

    public Page<QuestionVO> listQuestionByPage(QuestionQueryRequest questionQueryRequest) {
        String searchText = questionQueryRequest.getSearchText();
        int current = questionQueryRequest.getCurrent();
        int pageSize = questionQueryRequest.getPageSize();
        // 题目表的查询条件
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(searchText))
            queryWrapper.and(wrapper -> wrapper.like("title", searchText)).or().like("content",searchText);
        queryWrapper.orderByDesc("priority");
        // 根据题库查询题目列表接口
        Long questionBankId = questionQueryRequest.getBankId();
        if (questionBankId != null) {
            // 查询题库内的题目 id
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .select(QuestionBankQuestion::getQuestionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            List<QuestionBankQuestion> questionList = questionBankQuestionService.list(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(questionList)) {
                // 取出题目 id 集合
                Set<Long> questionIdSet = questionList.stream()
                        .map(QuestionBankQuestion::getQuestionId)
                        .collect(Collectors.toSet());
                // 复用原有题目表的查询条件
                queryWrapper.in("id", questionIdSet);
            }
        }
        // 查询数据库
        Page<Question> questionPage = this.page(new Page<>(current, pageSize), queryWrapper);
        List<QuestionVO> questionVOStream = questionPage.getRecords().stream().map(question -> {
            QuestionVO questionVO = new QuestionVO();
            BeanUtil.copyProperties(question, questionVO);
            return questionVO;
        }).collect(Collectors.toList());
        return new Page<QuestionVO>().setRecords(questionVOStream);
    }

    @Override
    public Page<QuestionVO> searchQuestionFromEs(QuestionQueryRequest queryRequest, HttpServletRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (queryRequest == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        String searchText = queryRequest.getSearchText();
        String tags = queryRequest.getTags();
        int current = queryRequest.getCurrent() - 1;
        int pageSize = queryRequest.getPageSize();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();
        //包含所有标签
        if (StringUtils.isNotBlank(tags)){
            List<String> tagList = JSONUtil.toList(tags, String.class);
            for (String tag : tagList) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tags", tag));
            }
        }
        //根据关键字匹配，标题、内容其中一个包含即可
        if (StringUtils.isNotBlank(searchText)){
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("answer", searchText));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        //排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        if (StringUtils.isNotBlank(sortField)){
            sortBuilder = SortBuilders.fieldSort(sortField);
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(sortOrder) ? SortOrder.ASC : SortOrder.DESC );
        }
        //分页
        PageRequest pageRequest = PageRequest.of(current, pageSize);
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withSorts(sortBuilder)
                .withPageable(pageRequest)
                .build();
        SearchHits<QuestionEsDTO> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, QuestionEsDTO.class);
        Page<QuestionVO> questionVOPage = new Page<>();
        questionVOPage.setTotal(searchHits.getTotalHits());
        List<QuestionVO> questionVOList = new ArrayList<>();
        if (searchHits.getTotalHits() > 0){
            List<SearchHit<QuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            for (SearchHit<QuestionEsDTO> searchHit : searchHitList) {
                QuestionEsDTO questionEsDTO = searchHit.getContent();
                QuestionVO questionVO = QuestionVO.entityToVo(QuestionEsDTO.dtoToObj(questionEsDTO));
                questionVOList.add(questionVO);
            }
        }
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }




    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteQuestions(List<Long> questionIdList) {
        if (CollUtil.isEmpty(questionIdList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "要删除的题目列表为空");
        }
        for (Long questionId : questionIdList) {
            boolean result = this.removeById(questionId);
            if (!result) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除题目失败");
            }
            // 移除题目题库关系
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .eq(QuestionBankQuestion::getQuestionId, questionId);
            result = questionBankQuestionService.remove(lambdaQueryWrapper);
            if (!result) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除题目题库关联失败");
            }
        }
    }

    @Override
    public QuestionVO getQuestion(Long id, HttpServletRequest request) {
        //默认ip作为查询键
        String ipAddress = NetUtils.getIpAddress(request);
        Long loginId = null;
        String key = ipAddress;
        //若用户登陆则以用户id作为键
        if (StpUtil.isLogin()){
            loginId = StpUtil.getLoginIdAsLong();
            key = loginId.toString();
        }
        if (netUtils.crawlerDetect(key)){
            //登陆状态下踢下线并封禁用户
            if (StpUtil.isLogin()){
                //踢下线
                StpUtil.logout();
                //设置用户状态为封号
                User user = new User();
                user.setId(loginId);
                user.setUserRole(UserConstant.BAN_ROLE);
                boolean updateBanUser = userService.updateById(user);
                if (!updateBanUser)
                    log.error("封禁用户 {} 失败",loginId);
            }
            //把ip拉入访问黑名单
            //todo 把ip更新至nacos
            BlackIpUtil.addBlackIp("easy-offer",ipAddress,request);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"禁止访问！");
        }
        Optional<Question> question = this.getOptById(id);
        QuestionVO questionVO = new QuestionVO();
        if (question.isPresent()){
            BeanUtil.copyProperties(question.get(),questionVO);
            return questionVO;
        }else {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"该题目不存在");
        }
    }


}




